<template>
  <el-form class="hotel_search_bar" inline>
    <!-- 查找城市 -->
    <el-form-item>
      <el-autocomplete
        clearable
        @clear="clearSearchCity"
        highlight-first-item
        :trigger-on-focus="false"
        v-model="cityName"
        :fetch-suggestions="querySearchAsync"
        placeholder="切换城市"
        @select="handleSelectCity"
        ref="autocompleteRef"
      ></el-autocomplete>
    </el-form-item>

    <!-- 入店时间 -->
    <el-form-item>
      <el-date-picker
        v-model="selectTime"
        type="daterange"
        range-separator="-"
        start-placeholder="入住日期"
        end-placeholder="离店日期"
        :picker-options="pickerOptions"
        @change="handleSelectTime"
        value-format="yyyy-MM-dd"
      ></el-date-picker>
    </el-form-item>

    <!-- 人数 -->
    <el-form-item>
      <el-popover
        :visible-arrow="false"
        placement="bottom-start"
        width="320"
        trigger="click"
        v-model="popoverVisible"
      >
        <el-row
          class="select_person"
          type="flex"
          justify="space-between"
          align="middle"
        >
          <span>每间</span>
          <el-row type="flex">
            <!-- 成人数量选择 -->
            <el-select size="mini" v-model="adult" placeholder="1 成人">
              <el-option
                v-for="item in 7"
                :key="item"
                :label="item + ' 成人'"
                :value="item + ' 成人'"
              >
                <span>{{ item }}</span>
              </el-option>
            </el-select>

            <!-- 儿童数量选择 -->
            <el-select size="mini" v-model="children" placeholder="0 儿童">
              <el-option
                v-for="item in 5"
                :key="item"
                :label="item - 1 + ' 儿童'"
                :value="item - 1 + ' 儿童'"
              >
                <span>{{ item - 1 }}</span>
              </el-option>
            </el-select>
          </el-row>
        </el-row>

        <el-row class="selectBtn" type="flex" justify="end">
          <el-button type="primary" size="mini" @click="handleSelectPerson"
            >确定</el-button
          >
        </el-row>

        <el-input
          slot="reference"
          readonly
          placeholder="人数未定"
          suffix-icon="el-icon-user"
          v-model="person"
        ></el-input>
      </el-popover>
    </el-form-item>

    <!-- 查看价格 -->
    <el-form-item>
      <el-button @click="searchHotel" type="primary">查看价格</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { mapState } from "vuex";
export default {
  computed: {
    ...mapState({
      city(state) {
        return state.hotel.city;
      },
      changeFlag(state) {
        return state.hotel.changeFlag;
      },
    }),
  },
  data() {
    return {
      // 查找的城市名
      cityName: "",
      // 酒店查询参数
      form: {
        // 城市id
        city: "",
        // 入店时间、
        enterTime: "",
        // 离店时间
        leftTime: "",
      },
      // 日期选择器选择的时间段
      selectTime: [],
      //   日期选择器配置项
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      // 弹出框显示隐藏
      popoverVisible: false,
      // 人数
      person: "",
      // 成人个数
      adult: "1 成人",
      // 儿童个数
      children: "0 儿童",
      query: "",
    };
  },
  mounted() {
    this.getCity();
  },
  methods: {
    // 请求城市数据
    async getCity() {
      const { data } = await this.$axios.get("/cities", {
        params: {
          name: this.cityName,
        },
      });
      // console.log(data);
      return data.data;
    },
    // 获取建议城市列表
    async querySearchAsync(queryString, callback) {
      let res = await this.getCity();
      //   处理数据，配置下拉框数据项  callback里面必须有value属性才行所以必须对数据进行改造
      const suggestions = res.map((item) => ({
        value: item.name,
        cityID: item.id,
      }));
      callback(suggestions);
      // 解决autocomplete输入框使用clearable属性时，清空后无法在自动获取数据问题
      this.$refs.autocompleteRef.handleFocus();
    },
    // 自动选择城市事件
    async handleSelectCity(item) {
      console.log(item);
      if (item.value === this.city) {
        // 请求城市信息
        let res = await this.getCity();
        // 修改请求数据
        this.form.city = res[0].id;
        // 向首页发送请求参数
        this.$emit("search-event", this.form);
      }
      this.$router.push("/hotel?" + this.query + "cityName=" + item.value);
      // this.$router.push("/hotel?city=" + item.value);
      setTimeout(() => {
        // 将城市保存到本地
        this.$store.commit("hotel/saveCity", item.value);
      }, 50);
    },
    // 选择时间事件
    handleSelectTime() {
      console.log(this.selectTime);
      if (this.selectTime) {
        //   设置查询参数中的时间参数
        this.form.enterTime = this.selectTime[0];
        this.form.leftTime = this.selectTime[1];
        //   调用查询方法
        // this.$emit("search-event", this.form);
      } else {
        this.form.enterTime = "";
        this.form.leftTime = "";
        //   调用查询方法
        // this.$emit("search-event", this.form);
      }
      this.query = `enterTime=${this.selectTime[0]}&leftTime=${this.selectTime[1]}&`;
    },

    // 选择人数事件
    handleSelectPerson() {
      this.person = this.adult + " / " + this.children;
      this.popoverVisible = false;
    },

    // 搜索酒店
    async searchHotel() {
      console.log(this.cityName);
      this.$router.push("/hotel?city=" + this.cityName);
      // 请求城市信息
      let res = await this.getCity();
      console.log(res);
      if (res.length === 0) {
        // 当前城市搜索不到
        this.$message.error("当前城市搜索不到，请重新搜索");
        this.form.city = null;
      } else if (res.length > 1) {
        // 搜索城市为空，显示所有城市
        this.form.city = "";
      } else {
        // 修改请求数据
        this.form.city = res[0].id;
        let name = /市$/.test(this.$route.query.city)
          ? this.$route.query.city
          : this.$route.query.city + "市";
        this.$store.commit("hotel/saveCity", name);
      }
    },
    // 清空搜索城市
    clearSearchCity() {
      this.$store.commit("hotel/saveCity", "");
      this.$router.push("/hotel");
      this.form.city = "";
    },
  },
  watch: {
    // 监听本地存储城市
    city: {
      async handler() {
        // 获取本地城市
        this.cityName = this.city;
        if (this.cityName === "") return;
        // 城市不为空，请求城市信息
        let res = await this.getCity();
        // console.log(res);
        // 修改请求数据
        this.form.city = res[0].id;
        // 向首页发送请求参数
        this.$emit("search-event", this.form);
        // console.log(res);
      },
      immediate: true,
    },
  },
};
</script>

<style lang="less" scoped>
.select_person {
  border-bottom: 1px solid #ddd;
  padding-bottom: 20px;

  .el-select {
    width: 90px;

    &:first-child {
      margin-right: 10px;
    }
  }
}
.selectBtn {
  margin-top: 20px;
}
</style>